package com.aphrodite.io.sip.transaction;

import com.aphrodite.io.sip.message.Message;
import com.aphrodite.io.sip.provider.ConnectionIdentifier;
import com.aphrodite.io.sip.provider.SipProvider;
import com.aphrodite.io.sip.provider.SipStack;
import com.aphrodite.io.sip.provider.TransactionIdentifier;
import com.aphrodite.io.sip.tools.Timer;

/**
 * Generic server transaction as defined in RFC 3261 (Section 17.2.2). A
 * TransactionServer is responsable to create a new SIP transaction that starts
 * with a request message received by the SipProvider and ends sending a final
 * response.<BR>
 * The changes of the internal status and the received messages are fired to the
 * TransactionListener passed to the TransactionServer object.<BR>
 * When costructing a new TransactionServer, the transaction type is passed as
 * String parameter to the costructor (e.g. "CANCEL", "BYE", etc..)
 */

public class TransactionServer extends Transaction {
	/** clearing timeout ("Timer J" in RFC 3261) */
	Timer clearing_to;

	/** last response message */
	Message response;

	/**
	 * the TransactionServerListener that captures the events fired by the
	 * TransactionServer
	 */
	TransactionServerListener transaction_listener;

	/** Costructs a new TransactionServer. */
	protected TransactionServer(SipProvider sip_provider) {
		super(sip_provider);
		transaction_listener = null;
		response = null;
	}

	/**
	 * Creates a new TransactionServer for the already received request
	 * <i>req</i>.
	 */
	public TransactionServer(SipProvider provider, Message req, TransactionServerListener listener) {
		super(provider);
		request = new Message(req);
		init(listener, request.getTransactionId(), request.getConnectionId());

		log.info(this, "start");
		changeStatus(STATE_TRYING);
		sip_provider.addSipProviderListener(transaction_id, this);
	}

	/** Creates a new TransactionServer of type <i>method</i>. */
	public TransactionServer(SipProvider sip_provider, String method, TransactionServerListener listener) {
		super(sip_provider);
		init(listener, new TransactionIdentifier(method), null);
	}

	/** Initializes timeouts and listener. */
	void init(TransactionServerListener listener, TransactionIdentifier transaction_id,
			ConnectionIdentifier connection_id) {
		this.transaction_listener = listener;
		this.transaction_id = transaction_id;
		this.connection_id = connection_id;
		this.response = null;
		clearing_to = new Timer(SipStack.transaction_timeout, "Clearing", this);
		log.info(this, "id: " + String.valueOf(transaction_id));
		log.info(this, "created");
	}

	/** Starts the TransactionServer. */
	public void listen() {
		if (statusIs(STATE_IDLE)) {
			log.info(this, "start");
			changeStatus(STATE_WAITING);
			sip_provider.addSipProviderListener(transaction_id, this);
		}
	}

	/**
	 * Method derived from interface SipListener. It's fired from the
	 * SipProvider when a new message is received for to the present
	 * TransactionServer.
	 */
	public void onReceivedMessage(SipProvider provider, Message msg) {
		if (msg.isRequest()) {
			if (statusIs(STATE_WAITING)) {
				request = new Message(msg);
				connection_id = msg.getConnectionId();
				sip_provider.removeSipProviderListener(transaction_id);
				transaction_id = request.getTransactionId();
				sip_provider.addSipProviderListener(transaction_id, this);
				changeStatus(STATE_TRYING);
				if (transaction_listener != null)
					transaction_listener.onTransRequest(this, msg);
				return;
			}
			if (statusIs(STATE_PROCEEDING) || statusIs(STATE_COMPLETED)) { // retransmission
				// of
				// the
				// last
				// response
				log.info(this, "response retransmission");
				sip_provider.sendMessage(response, connection_id);
				return;
			}
		}
	}

	/**
	 * Method derived from interface TimerListener. It's fired from an active
	 * Timer.
	 */
	public void onTimeout(Timer to) {
		try {
			if (to.equals(clearing_to)) {
				log.info(this, "Clearing timeout expired");
				sip_provider.removeSipProviderListener(transaction_id);
				changeStatus(STATE_TERMINATED);
				transaction_listener = null;
				// clearing_to=null;
			}
		} catch (Exception e) {
			log.error(this, "onTimeout", e);
		}
	}

	/** Sends a response message */
	public void respondWith(Message resp) {
		response = resp;
		if (statusIs(STATE_TRYING) || statusIs(STATE_PROCEEDING)) {
			sip_provider.sendMessage(response, connection_id);
			int code = response.getStatusLine().getCode();
			if (code >= 100 && code < 200 && statusIs(STATE_TRYING)) {
				changeStatus(STATE_PROCEEDING);
			}
			if (code >= 200 && code < 700) {
				changeStatus(STATE_COMPLETED);
				if (connection_id == null)
					clearing_to.start();
				else {
					log.info(this, "clearing_to=0 for reliable transport");
					onTimeout(clearing_to);
				}
			}
		}
	}

	/** Terminates the transaction. */
	public void terminate() {
		if (!statusIs(STATE_TERMINATED)) {
			clearing_to.halt();
			sip_provider.removeSipProviderListener(transaction_id);
			changeStatus(STATE_TERMINATED);
			transaction_listener = null;
			// clearing_to=null;
		}
	}

}
